<template>
  <div class="incomeRateChart flex-h-sb">
    <div class="chart">
      <div v-if="fitNetWorth_obj[nameKeyList[0]]&&fitNetWorth_obj[nameKeyList[0]].length>0">
        <div :id="id" :class="className" :style="{height:((height-40)*1.6)+'px',width:width}" />
        <div :id="`${id}1`" :style="{height:(height*0.72)+'px',width:width}" />
      </div>
      <div v-else class="flex-vh-center" style="height:565px;margin-top: 24px;">
        <img style="color: #666;" src="../../../../assets/nodata.png" alt="">
        <div style="color: #888;font-size: 22px;">此区间无两个以上净值数据，无法绘制曲线</div>
      </div>
      
      <div v-show="netWorth_obj[nameKeyList[0]]&&netWorth_obj[nameKeyList[0]].length" class="tip">
        <p>本区间最大回撤：{{sectionIncomeRate}}%</p>
        <p>({{sectionDate}})</p>
      </div>
    </div>
    
    <div v-if="fitNetWorth_obj[nameKeyList[0]]&&fitNetWorth_obj[nameKeyList[0]].length>0" class="control">
      <div v-show="showBeyondIncome" v-if="id!='contrastChart1'" class="beyondIncome flex-h-sb flex-v-center">
        <el-input :value="beyondIncome1" disabled style="width: 45%;"></el-input>
        <div class="shortline"></div>
        <el-select v-model="beyondIncome2" @change="beyondIncomeHandle" style="width: 45%;">
          <el-option
            v-for="item in indexNames"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div v-show="showBeyondIncome" v-else class="beyondIncome flex-h-sb flex-v-center">
        <el-select v-model="beyondIncome1" @change="beyondIncomeHandle" style="width: 45%;">
          <el-option
            v-for="item in indexNames1"
            :key="item.key"
            :label="item.name"
            :value="item.gId"
            :disabled="item.disabled">
          </el-option>
        </el-select>
        <i class="iconfont icon-zhihuan" @click="transformBeyondIncomeHandle"></i>
        <el-select v-model="beyondIncome2" @change="beyondIncomeHandle" style="width: 45%;">
          <el-option
            v-for="item in indexNames2"
            :key="item.key"
            :label="item.name"
            :value="item.gId"
            :disabled="item.disabled">
          </el-option>
        </el-select>
      </div>
      <div class="legend" :class="{'mt16': showBeyondIncome}">
        <div class="card flex-h-sb flex-v-center" v-for="(item, i) in nameLegends" :key="i">
          <div class="left flex-v-center">
            <el-checkbox style="margin: 2px 0 0 14px;" class="flex-v-center" :disabled="item.disabled" v-model="item.status" @change="legendHandle(item.key)"></el-checkbox>
            <div class="legend-name">
              <p v-if="!item.contrast_type" style="padding-left: 6px;">{{item.name}}</p>
              <p v-else style="padding-left: 6px;">{{legendTypeCom(item.contrast_type)}}{{item.name}}</p>
              <div class="line" :style="`border: 1px solid ${item.color};`"></div>
            </div>
          </div>
          <div class="right">
            <p>{{legendIncome(item.key)}}（年化{{legendAnnualizedIncome(item.key)}}）</p>
            <p>最大回撤：{{legendMaxBack(item.key)}}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import resize from '@/components/Charts/mixins/resize'
import { findClassifyNetworthByClassifyIdPlus, findStrategyIntersection } from '@/api/groupManage'
import { findCompositionStrategyIntersection, findCompareNetworthByClassifyIdPlus, findCompareIntersection } from '@/api/contrast'
import { yAxisNumber, xReturnZero, randomStr, chartDateFreq, getWeekData, getMonthData, listAfterClearNull } from '@/utils/pro'
import { findCompositionNetworthByCompositionIdNew, getStrategyAndCompositionByCompositionIdPlus, findClassifyIntersection } from '@/api/combManage'
import { parseTime, debounce } from '@/utils'
import { differenceInCalendarMonths } from 'date-fns'


export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '200px'
    },
    height: {
      type: Number,
      default: 200
    },
    id_index: {
      type: Array,
      default: () => {
        return []
      }
    },
    ids: {
      type: String | Number,
      required: true
    },
    typePage: {
      type: String,
      default: ''
    },
    userId: {
      type: String | Number,
      default: ''
    },
    name1: {
      type: String,
      default: '拟合'
    },
    name2: {
      type: String,
      default: '风险'
    },
    indexNames: {
      type: Array,
      default: () => {
        return []
      }
    },
    chart_date: {
      type: Array,
      default: () => {
        return []
      }
    },
    sameSection: {  // 同区间
      type: Boolean,
      default: false
    },
    dateFreq: {  // 计算频率
      type: Number,
      default: undefined
    },
    defaultDateFreq: {  // 默认频率
      type: Number,
      default: undefined
    },
    showBeyondIncome: {  // 超额收益
      type: Boolean,
      default: false
    },
    contrastList: { // 对比详情专属
      type: Array,
      default: () => {
        return []
      }
    },
  },
  data() {
    return {
      beyondIncome1: '',
      beyondIncome2: '',
      indexNames1: [],
      indexNames2: [],

      chart: null,
      chart1: null,
      startTime: '',
      endTime: '',

      currentObj1: {},
      currentObj2: {},
      
      xDate: [], // y轴
      fitNetWorth_obj: {}, // 收益集合
      netWorth_obj: {}, // 回撤集合

      isIndexList: [], // 记录指数名称数组
      legendStatus: {}, // 记录图例选择状态
      firstInPage: 1, // 记录首次进入页面用

      nameKeyObj: {}, // 曲线名称重复问题，用唯一key记录
      nameKeyList: [], // 唯一key列表
      nameLegends: [], // 自定义图例属性

      day_xDate: [], // 日频y轴
      day_fitNetWorth_obj: {}, // 日频收益集合
      day_netWorth_obj: {}, // 日频回撤集合

      week_xDate: [], // 周频y轴
      week_fitNetWorth_obj: {}, // 周频收益集合
      week_netWorth_obj: {}, // 周频回撤集合

      month_xDate: [], // 月频y轴
      month_fitNetWorth_obj: {}, // 月频收益集合
      month_netWorth_obj: {}, // 月频回撤集合

      color_list: [
        'rgba(225,103,86,1)', 'rgba(129,183,236,1)', 'rgba(173,224,255,1)', 'rgba(255,155,203,1)',
        '#cca4e3','#96ce54','#ff4777','#1685a9','#eedeb0','#0aa344','#f00056','#4b5cc4','#e29c45', 'rgba(238,203,87,1)',
        '#21a675','#f9906f','#44cef6','#ae7000','#057748','#f05654','#a1afc9','#a78e44','#00e500','#c93756','#065279','#d9b611',
        '#9b4400','#00e09e','#8c4356','#3b2e7e','#7fecad','#f20c00','#426666','#827100','#a4e2c6','#9d2933','#815476',
        '#6e511e','#0eb83a','#b36d61','#edd1d8','#48c0a3','#bf242a','#4c221b','#549688','#60281e','#003371','#789262',
        '#ff7500','#801dae','#758a99','#ffa631','#4c8dae','#50616d','#b0a4e3','#424c50','#fff143','#bce672'
      ],
      contrast_type_list: ['策略', '分类', '组合'],
    }
  },
  computed: {
    legendTypeCom() {
      return (type) => {
        if(type<4) {
          return '[' + this.contrast_type_list[type-1] + ']'
        }else {
          return ''
        }
      }
    },
    sectionIncomeRate() {
      if(!(this.chart1 && this.netWorth_obj[this.nameKeyList[0]])) {
        return ''
      }
      const key = this.nameLegends.find(item => item.main==1).key
      const start_i = this.chart1.getModel().option.dataZoom[0].startValue
      const end_i = this.chart1.getModel().option.dataZoom[0].endValue
      const list = this.netWorth_obj[key].slice(start_i, end_i+1)
      const min = Math.min.apply(null, list)
      return min
    },
    sectionDate() {
      if(!(this.chart1 && this.netWorth_obj[this.nameKeyList[0]])) {
        return ''
      }
      const key = this.nameLegends.find(item => item.main==1).key
      const start_i = this.chart1.getModel().option.dataZoom[0].startValue
      const end_i = this.chart1.getModel().option.dataZoom[0].endValue
      const list = this.netWorth_obj[key].slice(start_i, end_i+1)
      const min = Math.min.apply(null, list)
      const i = list.findIndex(item => item==min)
      return this.xDate[i+start_i]
    },
    legendIncome() {
      return (key) => {
        const list = listAfterClearNull(this.currentObj1[key])[0]
        if(!list.length) {
          return '--'
        }else {
          return list[list.length-1] + '%'
        }
      }
    },
    legendAnnualizedIncome() {
      return (key) => {
        const list = listAfterClearNull(this.currentObj1[key])[0]
        if(!list.length) return '--'
        const start_i = this.chart ? this.chart.getModel().option.dataZoom[0].startValue : 0
        const end_i = this.chart ? this.chart.getModel().option.dataZoom[0].endValue : list.length-1
        const dm = differenceInCalendarMonths(this.xDate[end_i], this.xDate[start_i]) ? differenceInCalendarMonths(this.xDate[end_i], this.xDate[start_i]) : 1
        const yearAnnualizedincomeRate = (list.slice(-1) / (dm/12)).toFixed(2)
        return yearAnnualizedincomeRate + '%'
      }
    },
    legendMaxBack() {
      return (key) => {
        const list = listAfterClearNull(this.currentObj2[key])[0]
        if(!list.length) return '--'
        const min = Math.min.apply(null, list)
        return Math.abs(min) + '%'
      }
    }
  },
  watch: {
    typePage() {
      if(this.ids) {
        this.legendStatus = {}  // 清除组合穿透时勾选混乱状态
        this.nameKeyObj = {}
        this.nameKeyList = []
        this.nameLegends = []
        this.firstInPage = 1
        this.initPage(this.ids, this.chart_date)
      }
    },
    ids: {
      handler(id) {
        if(id || id == 0) {
          this.initPage(id, this.chart_date)
        }
      },
      deep: true,
      immediate: true
    },
    id_index: {
      handler(id) {
        if(id.length<6&&this.ids) {
          this.initPage(this.ids, this.chart_date)
        }
      },
      deep: true
    },
    chart_date: {
      handler(dates) {
        this.initPage(this.ids, dates)
      },
      deep: true
    },
    dateFreq(i) {
      if(i==1) {
        this.dayFreqHandle()
      }else if(i==2) {
        this.weekFreqHandle()
      }else if(i==3) {
        this.monthFreqHandle()
      }
    },
    showBeyondIncome(val) {
      if(val) {
        this.beyondIncomeHandle()
      }else {
        if(this.fitNetWorth_obj['111111']) {
          delete this.fitNetWorth_obj['111111']
          delete this.netWorth_obj['111111']
          delete this.nameKeyObj['111111']
          this.nameKeyList.shift()
          this.nameLegends.shift()
          this.clearNameLegendsDisabled()

          // 显示超额收益则把其他曲线关闭
          this.nameLegends.forEach((item, i) => {
            if(!i) {
              item.status = true
              this.legendStatus[item.key] = true
            }else {
              item.status = false
              this.legendStatus[item.key] = false
            }
          })

          this.chart && this.chart.dispose()
          this.chart1 && this.chart1.dispose()
          this.$nextTick(() => {
            this.initChart(this.fitNetWorth_obj, this.netWorth_obj)
          })
        }
      }
    },
    indexNames: {
      handler() {
        if(this.id=='contrastChart1') {
          const list = JSON.parse(JSON.stringify(this.indexNames))
          this.indexNames1 = list
          this.indexNames2 = list
          
          this.beyondIncome1 = list[0].gId
          this.beyondIncome2 = list[1].gId
        }else {
          this.beyondIncome1 = this.name1
          this.beyondIncome2 = this.indexNames[0].id
        }
      },
      deep: true,
      immediate: true
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart1.dispose()
    this.chart = null
    this.chart1 = null
  },
  methods: {
    async initPage(id, dates) {
      let axiosFun = Function
      const res = []  
      
      // 请求后台基础数据
      // if(!this.typePage) {
      // }else if(this.typePage == 'afterManageCom') {
      // }else
      if(this.typePage == 'groupManage') {
        if(!this.sameSection) {
          axiosFun = this.findClassifyNetworthByClassifyId
        }else {
          axiosFun = this.findStrategyIntersection
        }
      }else if(this.typePage == 'combManage') {
        if(!this.sameSection) {
          axiosFun = this.CombManagefindNetworthById
        }else {
          axiosFun = this.findClassifyIntersection
        }
      }else if(this.typePage == 'combManage-strategy') {
        if(!this.sameSection) {
          axiosFun = this.getStrategyAndCompositionByCompositionIdPlus
        }else {
          axiosFun = this.findCompositionStrategyIntersection
        }
      }else if(this.typePage == 'contrast') {
        if(!this.sameSection) {
          axiosFun = this.findCompareNetworthByClassifyIdPlus
        }else {
          axiosFun = this.findCompareIntersection
        }
      }
      res[0] = await axiosFun(id, dates)
      
      // 初始化显示数据和前端存储数据
      this.xDate = [], this.day_xDate = [], this.week_xDate = [], this.month_xDate = []
      this.fitNetWorth_obj = {}, this.day_fitNetWorth_obj = {}, this.week_fitNetWorth_obj = {}, this.month_fitNetWorth_obj = {}
      this.netWorth_obj = {}, this.day_netWorth_obj = {}, this.week_netWorth_obj = {}, this.month_netWorth_obj = {}

      // 在legendStatus置空前记录为false的nameKeyObj对象
      const _legendStatus_isFalse_nameList = []
      const legendStatus_list  = Object.keys(this.legendStatus)
      if(legendStatus_list.length) {
        legendStatus_list.map(key => {
          if(!this.legendStatus[key]) {
            _legendStatus_isFalse_nameList.push(this.nameKeyObj[key])
          }
        })
      }
      this.nameKeyObj = {}
      this.nameKeyList = []
      this.nameLegends = []

      this.isIndexList = res[0].body[0].item.filter(e => e.isIndex).map(e => e.key)
      res[0].body[0].item.map((item, i) => {  // 用key记录曲线name，规避name重复
        const name = item.key
        const key = randomStr(8)
        this.nameKeyObj[key] = name
        this.nameKeyList.push(key)
        if(_legendStatus_isFalse_nameList.indexOf(name)!=-1) this.legendStatus[key] = false
        this.nameLegends.push({
          main: i ? 0 : 1, // 主线为1
          name: name,
          key: key,
          id: item.id,
          color: this.color_list[i],
          status: this.legendStatus[key]!=undefined ? this.legendStatus[key] : true,
          contrast_type: item.type ? item.type : null
        })
      })
      if(res[0].body&&res[0].body.length>0) {
        const n_list = []
        const base_incomeRate_drawDown_list = []
        res[0].body.forEach((items, index) => {
          if(this.typePage == 'groupManage' || this.typePage == 'combManage' || this.typePage == 'combManage-strategy' || this.typePage == 'contrast') {
            this.xDate.push(parseTime(items.date))
            items.item.map((el, i) => {
              el.pnl = el.pnl ? Number(el.pnl) : 0
              if(n_list[i]==undefined) n_list[i] = 0
              if(el.isIndex) {
                n_list[i] = (1+n_list[i])*(1+el.pnl)-1
              }else {
                if(index>0) n_list[i] = Number(n_list[i])+el.pnl
                // 首次进入页面图例状态 图例只显示主线和指数线
                if(this.firstInPage==1 && el.key!=this.name1 && index==0) {
                  if(this.id=='contrastChart1') {
                    this.nameLegends.forEach((item, nl_i) => {
                      if(item.contrast_type===el.type&&item.id===el.id) {
                        this.nameLegends[nl_i].status = false
                        this.legendStatus[item.key] = false
                      }
                    })
                  }else {
                    this.nameLegends.forEach((item, nl_i) => {
                      if(!(item.main || item.contrast_type)) {
                        this.nameLegends[nl_i].status = false
                        this.legendStatus[item.key] = false
                      }
                    })
                  }
                }
              }
              el.incomeRate = el.netWorth!=null ? (n_list[i]*100).toFixed(2) : null
              if(!this.fitNetWorth_obj[this.nameKeyList[i]]) this.fitNetWorth_obj[this.nameKeyList[i]] = []
              if(!this.netWorth_obj[this.nameKeyList[i]]) this.netWorth_obj[this.nameKeyList[i]] = []
              this.fitNetWorth_obj[this.nameKeyList[i]].push(el.incomeRate)
              if(el.incomeRate == null) {
                this.netWorth_obj[this.nameKeyList[i]][index] = null
              }else if(Number(el.incomeRate)<Number(base_incomeRate_drawDown_list[i])) {
                if(el.isIndex) {
                  this.netWorth_obj[this.nameKeyList[i]][index] = (((el.incomeRate-base_incomeRate_drawDown_list[i])/(Number(base_incomeRate_drawDown_list[i])+100))*100).toFixed(2)
                }else {
                  this.netWorth_obj[this.nameKeyList[i]][index] = (el.incomeRate-base_incomeRate_drawDown_list[i]).toFixed(2)
                }
              }else {
                base_incomeRate_drawDown_list[i] = el.incomeRate
                this.netWorth_obj[this.nameKeyList[i]][index] = 0
              }
            })
          }
        })
        this.currentObj1 = this.fitNetWorth_obj
        this.currentObj2 = this.netWorth_obj

        const _defaultDateFreq = chartDateFreq(this.xDate)
        this.$emit('update:defaultDateFreq', _defaultDateFreq)
        const _dateFreq = _defaultDateFreq
        _dateFreq == 1 ? this.day_xDate=this.xDate : _dateFreq == 2 ? this.week_xDate=this.xDate : this.month_xDate=this.xDate
        _dateFreq == 1 ? this.day_fitNetWorth_obj=this.fitNetWorth_obj : _dateFreq == 2 ? this.week_fitNetWorth_obj=this.fitNetWorth_obj : this.month_fitNetWorth_obj=this.fitNetWorth_obj
        _dateFreq == 1 ? this.day_netWorth_obj=this.netWorth_obj : _dateFreq == 2 ? this.week_netWorth_obj=this.netWorth_obj : this.month_netWorth_obj=this.netWorth_obj

        if(this.dateFreq!=_dateFreq) {
          this.$emit('update:dateFreq', _dateFreq)
        }else {
          if(this.dateFreq==1) {
            this.dayFreqHandle()
          }else if(this.dateFreq==2) {
            this.weekFreqHandle()
          }else {
            this.monthFreqHandle()
          }
        }
      }
    },
    
    initChart(obj1, obj2) {
      this.chart = echarts.init(document.getElementById(this.id))
      this.chart1 = echarts.init(document.getElementById(this.id+'1'))

      let all_list_obj1 = []
      const series_obj1 = []
      const series_obj2 = []

      const start_i = this.chart.getModel() ? this.chart.getModel().option.dataZoom[0].startValue : 0
      const end_i = this.chart.getModel() ? this.chart.getModel().option.dataZoom[0].endValue : obj1[this.nameKeyList[0]].length
      const view_obj = [{}, {}]

      if(Object.keys(obj1).length) {
        Object.keys(obj1).forEach((key, i) => {
          view_obj[0][this.nameKeyObj[key]] = obj1[key].slice(start_i, end_i)
          const item = obj1[key]
          if(this.legendStatus[this.nameKeyList[i]]==undefined||this.legendStatus[this.nameKeyList[i]]) all_list_obj1 = [...all_list_obj1, ...item]  // 收集参与y轴计算的数据
          series_obj1.push({
            name: key,
            type: 'line',
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            lineStyle: {
              width: 1.6
            },
            itemStyle: {
              // color: this.color_list[i]
              color: this.nameLegends[i].color
            },
            data: item,
            connectNulls: true
          })
        })
      }
      const yVal = yAxisNumber(all_list_obj1)

      if(Object.keys(obj2).length) {
        Object.keys(obj2).forEach((key, i) => {
          view_obj[1][this.nameKeyObj[key]] = obj2[key].slice(start_i, end_i)
          let _key = key
          if(i==0 && this.id=="groupManageChart1" && key!=Object.keys(obj1)[0]) _key = Object.keys(obj1)[0] // 解决 分类详情下只有一条策略时，回撤标题为'默认分类'问题  兼容接口代码
          const item = obj2[key]
          series_obj2.push({
            name: _key,
            type: 'line',
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            lineStyle: {
              width: 1.6
            },
            itemStyle: {
              // color: this.color_list[i]
              color: this.nameLegends[i].color
            },
            // rgba(225,103,86,1)
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                offset: 0,
                color: _key=='风险'||this.nameLegends[i].main||_key!=key ? 'rgba(225,103,86,0.2)' : 'rgba(0,0,0,0)'
              }, {
                offset: 1,
                color: _key=='风险'||this.nameLegends[i].main||_key!=key ? 'rgba(225,103,86,0.2)' : 'rgba(0,0,0,0)'
              }])
            },
            data: item,
            connectNulls: true
          })
          if(this.nameLegends[i].main) {
            series_obj2[i].markLine = {
              // animation: false,
              data: [
                { 
                  type: 'min'
                }
              ],
              label: {
                show: false
              }
            }
          }
        })
      }
      view_obj[2] = this.xDate.slice(start_i, end_i)
      this.$emit('viewObj', view_obj)

      this.chart.setOption({
        title: {
          left: 52,
          text: '收益',
          top: 10,
          textStyle: {
            color: '#595959',
            fontWeight: 400
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            textStyle: {
              color: '#fff'
            }
          },
          formatter: (params) => {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${params[0].name}</div>`
            for (let i = 0; i < params.length; i += 1) {
              if(params[i].data!=null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${this.nameKeyObj[params[i].seriesName]}</span> 
                      <span style="margin-left: 10px;font-weight: bold;"> ${params[i].data}%</span>
                      </div>`
              }
            }
            return str
          }
        },
        grid: {
          top: 10,
          left: 55,
          right: 10,
          bottom: '6%',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          show: false,
          orient: 'vertical',
          x: 'left',
          left: '82%',
          top: '10%',
          textStyle: {
            color: '#90979c',
            fontSize: 11,
          },
          formatter: (name) => {
            const start_i = this.chart.getModel().option.dataZoom[0].startValue
            const end_i = this.chart.getModel().option.dataZoom[0].endValue
            const obj = this.chart.getOption().series.find(item => item.name==name)
            const dm = differenceInCalendarMonths(this.xDate[end_i], this.xDate[start_i]) ? differenceInCalendarMonths(this.xDate[end_i], this.xDate[start_i]) : 1
            const yearAnnualizedincomeRate = (obj.data[end_i] / (dm/12)).toFixed(2)
            return obj.data[end_i] ? this.nameKeyObj[name] +'   '+ obj.data[end_i] + '%' + ' (年化:' + yearAnnualizedincomeRate + '%)' : this.nameKeyObj[name] +'   '+ '--'
          },
          selected: this.legendStatus
        },
        calculable: true,
        xAxis: [{
          show: false,
          type: 'category',
          boundaryGap: false, // 折线从x轴起始开始走
          splitNumber: 8,
          axisLine: {
            lineStyle: {
              color: '#90979c'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: true,
            alignWithLabel: true,
            interval: 'auto'
          },
          splitArea: {
            show: false
          },
          axisLabel: {
            show: false,
            interval: 'auto'
          },
          data: this.xDate,
        }],
        yAxis: [
          {
            type: 'value',
            min: yVal[0],
            max: yVal[1],
            interval: yVal[2],
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#90979c'
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value.toFixed(2) + '%'
              }
            },
            splitArea: {
              show: false
            }
          }
        ],
        dataZoom: [{
          type: 'inside',
          start: 0,
          end: 100,
          zoomLock: true
        }, {
          show: false,
          brushSelect: false,
          realtime: true, // 实时更新系列的视图
          height: '7%',
          bottom: '1%',
        }],
        series: series_obj1
      })
    
      this.chart1.setOption({
        title: {
          left: 52,
          text: '回撤',
          top: 10,
          textStyle: {
            color: '#595959',
            fontWeight: 400
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            textStyle: {
              color: '#fff'
            }
          },
          formatter: (params) => {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${params[0].name}</div>`
            for (let i = 0; i < params.length; i += 1) {
              if(params[i].data!=null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${this.nameKeyObj[params[i].seriesName]}</span> 
                      <span style="margin-left: 10px;font-weight: bold;"> ${params[i].data}%</span>
                      </div>`
              }
            }
            return str
          }
        },
        grid: {
          top: 10,
          left: 55,
          right: 10,
          bottom: '37%',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          show: false,
          orient: 'vertical',
          x: 'left',
          left: '82%',
          top: '2%',
          textStyle: {
            color: '#90979c',
            fontSize: 11,
          },
          formatter: (name) => {
            const start_i = this.chart1.getModel().option.dataZoom[0].startValue
            const end_i = this.chart1.getModel().option.dataZoom[0].endValue
            const list = this.netWorth_obj[name].slice(start_i, end_i+1)
            const min = Math.min.apply(null, list)
            return this.nameKeyObj[name] +'   '+ min + '%'
          },
          selected: this.legendStatus
        },
        calculable: true,
        xAxis: [{
          type: 'category',
          boundaryGap: false, // 折线从x轴起始开始走
          splitNumber: 8,
          axisLine: {
            show: false,
            lineStyle: {
              color: '#90979c'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: false,
            alignWithLabel: true,
            interval: 'auto'
          },
          splitArea: {
            show: false
          },
          axisLabel: {
            interval: 'auto',
            margin: 20,
          },
          data: this.xDate,
        }],
        yAxis: [
          {
            type: 'value',
            splitNumber: 4,
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#90979c'
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value+'%'
              }
            },
            splitArea: {
              show: false
            }
          }
        ],
        dataZoom: [{
          type: 'inside',
          start: 0,
          end: 100,
          zoomLock: true
        }, {
          brushSelect: false,
          realtime: true, // 实时更新系列的视图
          height: '14%',
          bottom: '1%',
        }],
        series: series_obj2
      })

      if(this.typePage=='groupManage' && this.name1=='模拟组合') {  // 对比页面
        this.$emit('loadingOk')
      }
    
      this.chart.on('datazoom', debounce(() => {
        const baseline_i = this.chart.getModel().option.dataZoom[0].startValue
        const end_i = this.chart.getModel().option.dataZoom[0].endValue
        let op = this.chart.getOption()
        let op1 = this.chart1.getOption()
        const op_res = xReturnZero(this.fitNetWorth_obj, this.netWorth_obj, op, op1, baseline_i, end_i, this.isIndexList)
        op = op_res.op
        op1 = op_res.op1

        // 风险指标
        const view_obj = [{}, {}]
        this.currentObj1 = {}
        this.currentObj2 = {}
        Object.keys(this.fitNetWorth_obj).forEach(key => {
          const _obj1 = op.series.filter(item => item.name==key)[0]
          const _obj2 = op1.series.filter(item => item.name==key)[0]
          view_obj[0][this.nameKeyObj[key]] = _obj1.data.slice(baseline_i, end_i+1)
          view_obj[1][this.nameKeyObj[key]] = _obj2.data.slice(baseline_i, end_i+1)

          this.currentObj1[key] = view_obj[0][this.nameKeyObj[key]]
          this.currentObj2[key] = view_obj[1][this.nameKeyObj[key]]
        })
        view_obj[2] = this.xDate.slice(baseline_i, end_i+1)
        this.$emit('viewObj', view_obj)

        const yVal = yAxisNumber(op_res.all_list_obj1)
        op.yAxis[0].min = yVal[0]
        op.yAxis[0].max = yVal[1]
        op.yAxis[0].interval = yVal[2]
        op1.dataZoom[0].start = op.dataZoom[0].start
        op1.dataZoom[0].end = op.dataZoom[0].end
        op1.dataZoom[1].start = op.dataZoom[1].start
        op1.dataZoom[1].end = op.dataZoom[1].end
        this.chart.setOption(op)
        this.chart1.setOption(op1)
      }, 500))

      this.chart1.on('datazoom', debounce(() => {
        const baseline_i = this.chart1.getModel().option.dataZoom[0].startValue
        const end_i = this.chart1.getModel().option.dataZoom[0].endValue
        let op = this.chart.getOption()
        let op1 = this.chart1.getOption()
        const op_res = xReturnZero(this.fitNetWorth_obj, this.netWorth_obj, op, op1, baseline_i, end_i, this.isIndexList)
        op = op_res.op
        op1 = op_res.op1

        // 风险指标 & 获取当前显示的数据
        const view_obj = [{}, {}]
        this.currentObj1 = {}
        this.currentObj2 = {}
        Object.keys(this.fitNetWorth_obj).forEach(key => {
          const _obj1 = op.series.filter(item => item.name==key)[0]
          const _obj2 = op1.series.filter(item => item.name==key)[0]
          view_obj[0][this.nameKeyObj[key]] = _obj1.data.slice(baseline_i, end_i+1)
          view_obj[1][this.nameKeyObj[key]] = _obj2.data.slice(baseline_i, end_i+1)

          this.currentObj1[key] = view_obj[0][this.nameKeyObj[key]]
          this.currentObj2[key] = view_obj[1][this.nameKeyObj[key]]
        })
        view_obj[2] = this.xDate.slice(baseline_i, end_i+1)
        this.$emit('viewObj', view_obj)

        const yVal = yAxisNumber(op_res.all_list_obj1)
        op.yAxis[0].min = yVal[0]
        op.yAxis[0].max = yVal[1]
        op.yAxis[0].interval = yVal[2]
        op.dataZoom[0].start = op1.dataZoom[0].start
        op.dataZoom[0].end = op1.dataZoom[0].end
        op.dataZoom[1].start = op1.dataZoom[1].start
        op.dataZoom[1].end = op1.dataZoom[1].end
        this.chart.setOption(op)
        this.chart1.setOption(op1)
      }, 500))
      
      this.chart.on('legendselectchanged', (obj) => {
        let op = this.chart.getOption()
        let op1 = this.chart1.getOption()
        op1.legend[0].selected = obj.selected

        // 记录图例状态
        this.savaLegendStatus(obj.selected)

        const baseline_i = this.chart1.getModel().option.dataZoom[0].startValue
        const end_i = this.chart1.getModel().option.dataZoom[0].endValue
        const op_res = xReturnZero(this.fitNetWorth_obj, this.netWorth_obj, op, op1, baseline_i, end_i, this.isIndexList)
        op = op_res.op
        op1 = op_res.op1
        const yVal = yAxisNumber(op_res.all_list_obj1)
        op.yAxis[0].min = yVal[0]
        op.yAxis[0].max = yVal[1]
        op.yAxis[0].interval = yVal[2]
        this.chart.setOption(op)
        this.chart1.setOption(op1)
      })

      this.chart1.on('legendselectchanged', (obj) => {
        let op = this.chart.getOption()
        let op1 = this.chart1.getOption()
        op.legend[0].selected = obj.selected

        // 记录图例状态
        this.savaLegendStatus(obj.selected)

        const baseline_i = this.chart1.getModel().option.dataZoom[0].startValue
        const end_i = this.chart1.getModel().option.dataZoom[0].endValue
        const op_res = xReturnZero(this.fitNetWorth_obj, this.netWorth_obj, op, op1, baseline_i, end_i, this.isIndexList)
        op = op_res.op
        op1 = op_res.op1
        const yVal = yAxisNumber(op_res.all_list_obj1)
        op.yAxis[0].min = yVal[0]
        op.yAxis[0].max = yVal[1]
        op.yAxis[0].interval = yVal[2]
        this.chart.setOption(op)
        this.chart1.setOption(op1)
      })

      this.chart.on('highlight', (params) => {
        const obj = params.batch[0]
        this.chart1.dispatchAction({
          type: 'showTip',
          seriesIndex: obj.seriesIndex,
          dataIndex: obj.dataIndex
        })
      })
      this.chart1.on('highlight', (params) => {
        const obj = params.batch[0]
        this.chart.dispatchAction({
          type: 'showTip',
          seriesIndex: obj.seriesIndex,
          dataIndex: obj.dataIndex
        })
      })

      this.chart.on('globalout', () => {
        this.chart1.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: -1
        })
      })
      this.chart1.on('globalout', () => {
        this.chart.dispatchAction({
          type: 'showTip',
          seriesIndex: 0,
          dataIndex: -1
         })
      })
    
      this.firstInPage++
    },

    beyondIncomeHandle() {
      if(this.beyondIncome1==''||this.beyondIncome2=='') return
      this.clearNameLegendsDisabled()
      let name1 = ''
      let name2 = ''
      let key1 = ''
      let key2 = ''
      // 找到选中的两个类目的key
      if(this.id!='contrastChart1') {
        name1 = this.name1
        name2 = this.indexNames.find(item => item.id==this.beyondIncome2).name
        this.nameLegends.map((item, i) => {
          if(item.name==name1) {
            this.nameLegends[i].status = true
            this.nameLegends[i].disabled = true
            key1 = item.key
          }else if(item.name==name2) {
            this.nameLegends[i].status = true
            this.nameLegends[i].disabled = true
            key2 = item.key
          }else {  // 显示超额收益则把其他曲线关闭
            this.nameLegends[i].status = false
            this.legendStatus[this.nameLegends[i].key] = false
          }
        })
      }else {
        const list = []
        this.indexNames1.forEach((item, i) => {
          this.indexNames1[i].disabled = false
          this.indexNames2[i].disabled = false
          if(item.gId == this.beyondIncome2) item.disabled = true
          if(item.gId == this.beyondIncome1) list.push({ id: item.id, type: item.type })
          if(this.indexNames2[i].gId == this.beyondIncome1) this.indexNames2[i].disabled = true
          if(this.indexNames2[i].gId == this.beyondIncome2) list.push({ id: this.indexNames2[i].id, type: this.indexNames2[i].type })
        })
        this.nameLegends.forEach((nl, i) => {
          if(nl.id==list[0].id&&nl.contrast_type==list[0].type) {
            this.nameLegends[i].status = true
            this.nameLegends[i].disabled = true
            key1 = nl.key
          }else if(nl.id==list[1].id&&nl.contrast_type==list[1].type) {
            this.nameLegends[i].status = true
            this.nameLegends[i].disabled = true
            key2 = nl.key
          }else {
            this.nameLegends[i].status = false
            this.legendStatus[this.nameLegends[i].key] = false
          }
        })
      }
      this.legendStatus[key1] = true
      this.legendStatus[key2] = true

      this.nameKeyObj['111111'] = '超额收益'
      if(this.nameKeyList[0]!='111111') this.nameKeyList.unshift('111111')
      if(this.nameLegends[0].key!='111111') {
        this.nameLegends.unshift({
          color: '#F6BD16',
          key: '111111',
          name: '超额收益',
          status: true,
          disabled: true
        })
      }
      this.nameLegends[0].status = true
      this.legendStatus['111111'] = true

      this.fitNetWorth_obj['111111'] = []
      this.netWorth_obj['111111'] = []
      let base_val = 0
      this.fitNetWorth_obj[key1].forEach((e, i) => {
        if(e!=null && this.fitNetWorth_obj[key2][i]!=null) {
          const num = (e - this.fitNetWorth_obj[key2][i]).toFixed(2)
          this.fitNetWorth_obj['111111'].push(num)
          if(Number(num)>base_val) {
            base_val = Number(num)
            this.netWorth_obj['111111'].push(0)
          }else {
            this.netWorth_obj['111111'].push((num - base_val).toFixed(2))
          }
        }else {
          this.fitNetWorth_obj['111111'].push(null)
          this.netWorth_obj['111111'].push(null)
        }
      })
      this.chart && this.chart.dispose()
      this.chart1 && this.chart1.dispose()
      this.$nextTick(() => {
        this.initChart(this.fitNetWorth_obj, this.netWorth_obj)
      })
    },

    transformBeyondIncomeHandle() {
      const val = this.beyondIncome1
      this.beyondIncome1 = this.beyondIncome2
      this.beyondIncome2 = val
      this.beyondIncomeHandle()
    },

    legendHandle(name) {
      this.chart.dispatchAction({
        type: 'legendToggleSelect',
        name
      })
    },
    
    dayFreqHandle() {
      this.xDate = this.day_xDate
      this.fitNetWorth_obj = this.day_fitNetWorth_obj
      this.netWorth_obj = this.day_netWorth_obj
      // 如果超额曲线显示且对应指数也存在, 则保留超额曲线
      let tag = false
      if(this.id=='contrastChart1') {
        const a = this.indexNames1.findIndex(item => item.gId==this.beyondIncome1)!=-1
        const b = this.indexNames2.findIndex(item => item.gId==this.beyondIncome2)!=-1
        tag = this.showBeyondIncome&&a&&b
      }else {
        tag = this.showBeyondIncome&&this.id_index.indexOf(this.beyondIncome2)!=-1
      }
      if(tag) {
        this.beyondIncomeHandle()
      }else {
        this.chart && this.chart.dispose()
        this.chart1 && this.chart1.dispose()
        this.$nextTick(() => {
          this.initChart(this.fitNetWorth_obj, this.netWorth_obj)
        })
      }
    },
    weekFreqHandle() {
      let res = []
      if(this.firstInPage==1) {
        res = getWeekData(this.week_xDate, this.week_fitNetWorth_obj, this.week_netWorth_obj)
        this.xDate = res[0]
        this.week_xDate = res[0]
        this.fitNetWorth_obj = res[1]
        this.week_fitNetWorth_obj = res[1]
        this.netWorth_obj = res[2]
        this.week_netWorth_obj = res[2]
      }else {
        if(this.week_xDate.length && this.xDate.length) {
          this.xDate = this.week_xDate
          this.fitNetWorth_obj = this.week_fitNetWorth_obj
          this.netWorth_obj = this.week_netWorth_obj
        }else if(this.day_xDate.length) {
          res = getWeekData(this.day_xDate, this.day_fitNetWorth_obj, this.day_netWorth_obj)
          this.xDate = res[0]
          this.week_xDate = res[0]
          this.fitNetWorth_obj = res[1]
          this.week_fitNetWorth_obj = res[1]
          this.netWorth_obj = res[2]
          this.week_netWorth_obj = res[2]
        }else {
          this.week_xDate = this.xDate
          this.week_fitNetWorth_obj = this.fitNetWorth_obj
          this.week_netWorth_obj = this.netWorth_obj
        }
      }
      // 如果超额曲线显示且对应指数也存在, 则保留超额曲线
      if(this.showBeyondIncome&&this.id_index.indexOf(this.beyondIncome2)!=-1) {
        this.beyondIncomeHandle()
      }else {
        this.chart && this.chart.dispose()
        this.chart1 && this.chart1.dispose()
        this.$nextTick(() => {
          this.initChart(this.fitNetWorth_obj, this.netWorth_obj)
        })
      }
    },
    monthFreqHandle() {
      let res = []
      if(this.firstInPage==1) {
        res = getMonthData(this.day_xDate, this.day_fitNetWorth_obj, this.day_netWorth_obj)
        this.xDate = res[0]
        this.month_xDate = res[0]
        this.fitNetWorth_obj = res[1]
        this.month_fitNetWorth_obj = res[1]
        this.netWorth_obj = res[2]
        this.month_netWorth_obj = res[2]
      }else {
        if(this.week_xDate.length && this.xDate.length) {
          res = getMonthData(this.week_xDate, this.week_fitNetWorth_obj, this.week_netWorth_obj)
          this.xDate = res[0]
          this.month_xDate = res[0]
          this.fitNetWorth_obj = res[1]
          this.month_fitNetWorth_obj = res[1]
          this.netWorth_obj = res[2]
          this.month_netWorth_obj = res[2]
        }else if(this.day_xDate.length) {
          res = getMonthData(this.month_xDate, this.month_fitNetWorth_obj, this.month_netWorth_obj)
          this.xDate = res[0]
          this.month_xDate = res[0]
          this.fitNetWorth_obj = res[1]
          this.month_fitNetWorth_obj = res[1]
          this.netWorth_obj = res[2]
          this.month_netWorth_obj = res[2]
        }else {
          this.month_xDate = this.xDate
          this.month_fitNetWorth_obj = this.fitNetWorth_obj
          this.month_netWorth_obj = this.netWorth_obj 
        }
      }
      // 如果超额曲线显示且对应指数也存在, 则保留超额曲线
      if(this.showBeyondIncome&&this.id_index.indexOf(this.beyondIncome2)!=-1) {
        this.beyondIncomeHandle()
      }else {
        this.chart && this.chart.dispose()
        this.chart1 && this.chart1.dispose()
        this.$nextTick(() => {
          this.initChart(this.fitNetWorth_obj, this.netWorth_obj)
        })
      }
    },

    // 分类管理
    // 收益
    async findClassifyNetworthByClassifyId(classifyId, dates) {
      const res = await findClassifyNetworthByClassifyIdPlus({
        classifyId,
        indexTypes: this.id_index,
        startTime: dates ? dates[0] : '',
        endTime: dates ? dates[1] : ''
      })
      return res
    },
    // 分类管理同区间
    async findStrategyIntersection(classifyId, dates) {
      const res = await findStrategyIntersection({
        classifyId,
        indexTypes: this.id_index,
        startTime: dates ? dates[0] : '',
        endTime: dates ? dates[1] : ''
      })
      return res
    },

    // 组合
    async CombManagefindNetworthById(compositionId, dates) {
      const res = await findCompositionNetworthByCompositionIdNew({
        compositionId,
        indexTypes: this.id_index,
        startTime: dates ? dates[0] : '',
        endTime: dates ? dates[1] : ''
      })
      console.log('组合-分类拟合净值:', res)
      return res
    },
    async findClassifyIntersection(compositionId, dates) {
      const res = await findClassifyIntersection({
        compositionId,
        indexTypes: this.id_index,
        startTime: dates ? dates[0] : '',
        endTime: dates ? dates[1] : ''
      })
      console.log('组合-分类拟合净值同区间:', res)
      return res
    },
    async getStrategyAndCompositionByCompositionIdPlus(compositionId, dates) {
      const res = await getStrategyAndCompositionByCompositionIdPlus({
        compositionId,
        indexTypes: this.id_index,
        startTime: dates ? dates[0] : '',
        endTime: dates ? dates[1] : ''
      })
      console.log('组合-策略拟合净值:', res)
      return res
    },
    async findCompositionStrategyIntersection(compositionId, dates) {
      const res = await findCompositionStrategyIntersection({
        compositionId,
        indexTypes: this.id_index,
        startTime: dates ? dates[0] : '',
        endTime: dates ? dates[1] : ''
      })
      console.log('组合-策略拟合净值同区间:', res)
      return res
    },

    //对比 
    async findCompareNetworthByClassifyIdPlus(uuid, dates) {
      const res = await findCompareNetworthByClassifyIdPlus({
        uuid,
        indexTypes: this.id_index,
        startTime: dates ? dates[0] : '',
        endTime: dates ? dates[1] : ''
      })
      return res
    },
    // 对比同区间
    async findCompareIntersection(uuid, dates) {
      const res = await findCompareIntersection({
        uuid,
        indexTypes: this.id_index,
        startTime: dates ? dates[0] : '',
        endTime: dates ? dates[1] : ''
      })
      return res
    },
    

    // 记录图例状态
    savaLegendStatus(obj) {
      this.legendStatus = {}
      Object.keys(obj).map(key => {
        const status = obj[key]
        if(!status) this.legendStatus[key] = status
      })
    },
    // 清除图例不可选状态
    clearNameLegendsDisabled() {
      this.nameLegends.forEach((item, i) => {
        if(item.key!='111111') {
          this.nameLegends[i] = {
            ...item,
            disabled: false
          }
        }
      })
    },
    
  }
}
</script>

<style lang="scss" scoped>
.incomeRateChart {
  .chart {
    width: calc( 100% - 432px );
    position: relative;
    .tip {
      position: absolute;
      bottom: 76px;
      left: calc( 100% - 180px );
      color: #666;
      p { text-align: right; }
    }
  }
  .control {
    display: flex;
    flex-direction: column;
    margin-left: 24px;
    height: 586px;
    .beyondIncome {
      .shortline {
        width: 20px;
        border: 1px solid #D9D9D9;
      }
    }
    .legend {
      min-width: 432px;
      height: 100%;
      overflow: auto;
      background: #FAFAFA;
      border-radius: 8px;
      .card {
        height: 48px;
        cursor: pointer;
        padding: 0 13px 0 14px;
        box-shadow: inset 0px -1px 0px 0px #F0F0F0;
        &:hover {
          background: #FFFFFF;
          box-shadow: inset 0px -1px 0px 0px #F0F0F0;
        }
        .legend-name {
          .line {
            width: 28px;
            margin-left: 6px;
          }
        }
        .right {
          font-size: 12px;
          color: #8C8C8C;
          p {text-align: right;}
        }
      }
    }
    .mt16 {
      margin-top: 16px;
    }
    .icon-zhihuan { color: #1890FF; cursor: pointer; }
  }
}
</style>

